<?php
declare (strict_types=1);

namespace app\common\library;

/*
 * 返回响应数据
 * */

class Response
{

    private $http_code = 200; //默认http状态码
    private $type = 'json'; //默认返回的头信息，json
    private $code = 1; //默认返回的错误状态码,1标识成功,其他标识错误
    private $message = '成功';//默认的提示消息
    private $data = []; //返回的数据

    /*
     * @title 设置成功信息
     * @param array $data 数组
     * @param string $message 提示消息
     * @param int $http_code 返回的状态码
     * @return self
     * */
    public function success(array $data = [], string $message = '成功', int $http_code = 200): self
    {
        $this->code = 1;
        $this->data = $data;
        $this->message = $message;
        $this->http_code = $http_code;
        return $this;
    }

    /*
     * 设置错误信息
     * @param string $message 错误提示信息
     * @param int $status 状态码
     * @param int $http_code 返回的状态码
     * @return this
     * */
    public function error(string $message = '未知错误', int $code = 0, int $http_code = 200): self
    {
        $this->code = $code;
        $this->message = $message;
        $this->http_code = $http_code;
        return $this;
    }

    /*
     * @title 设置返回的数据的类型
     * @type string $type 返回数据的类型
     * @return this
     * */
    public function setType(string $type = 'jsonp'): self
    {
        $this->type = $type;
        return $this;
    }

    /*
     * @title 返回结果
     * @return mixed
     * */
    public function getResult()
    {
        $data['code'] = $this->code;
        $data['msg'] = $this->message;
        $data['data'] = $this->data;
        switch ($this->type) {
            case 'raw': //原样返回
                return $data;
                break;
            case 'raw_json': //原样返回json
                return json_encode($data);
                break;
            case 'json': // think json
                return json($data, $this->http_code);
                break;
            case 'jsonp'://think jsonp
                return jsonp($data, $this->http_code);
                break;
        }
        return '';
    }
}